//
//  NetworkTools+OAuth.swift
//  SinaWeibo
//
//  Created by celeste on 16/5/17.
//  Copyright © 2016年 celeste. All rights reserved.
//

import Foundation

/*
1. 没有参数,只有返回值的函数,在调用的时候直接用()
2. 使用计算型属性.直接返回某一个类型的结果
3. 计算型属性不能接参数,直接返回,阅读的语义会更好
*/

/// 网络工具 - 身份授权部分
extension NetworkTools {
    
    //    func oauthURL() -> NSURL {
    var oauthURL: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appkey)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    
    func loadAccessToken(code: String, finished: ([String: AnyObject]?)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": appkey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        request(.POST, URLString: urlString, parameter: params) { [weak self] result in
            
            // result是token的结果字典,是可选的  如果 用key在字典取值,必须保证字典存在
            guard let result = result,
                let uid = result["uid"] as? String,
                let access_token = result["access_token"] as? String else{
                    //在失败的时候一定要有完成回调
                    finished(nil)
                    return
            }
            //继续加载用户数据
            self?.loadUser(access_token, uid: uid, finished: { (userDict) -> () in
                
                guard var userDict = userDict else {
                    finished(nil)
                    return
                }
                for (k,v) in result {
                    userDict[k] = v
                }
                finished(userDict)
                
            })
            
        }
    }
}







